<?php
/**
 * Copyright (c) 2020
 * 摘    要：
 * 作    者：san
 * 修改日期：2020.04.03
 */

namespace App\Controller\Http;

use App\Constants\Constants;
use App\Library\Traits\Helper;
use App\Model\Environment;

class EnvironmentController extends BaseController
{
    /**
     * 获取环境列表
     */
    public function index()
    {
        try {
            $result = Environment::query(true)->get();
            return $this->response->showResults(Constants::RETURN_SUCCESS, t('message.12001'), $result);
        } catch (\Exception $exception) {
            return $this->response->showResults(Constants::SERVER_ERROR, $exception->getMessage(), []);
        }
    }

    /**
     * 新增环境
     */
    public function store()
    {
        try {
            $rules = [
                'name'  => 'required',
                'alias' => 'required'
            ];
            $this->validator($rules);
            $data = $this->combine(array_keys($rules));
            $res  = Environment::query(true)->insert($data);
            if (!$res) throw new \ErrorException(t('message.12002'));
            return $this->response->showResults(Constants::RETURN_SUCCESS, t('message.12001'), []);
        } catch (\Exception $exception) {
            return $this->response->showResults(Constants::SERVER_ERROR, $exception->getMessage(), []);
        }
    }

    /**
     * 更新环境
     */
    public function update()
    {
        try {
            $rules = [
                'id'    => 'required',
                'name'  => 'required',
                'alias' => 'required'
            ];
            $this->validator($rules);
            $id    = $this->request->input('id');
            $name  = $this->request->input('name');
            $alias = $this->request->input('alias');
            $res   = Environment::query(true)->where('id', $id)->update(['name' => $name, 'alias' => $alias]);
            if (!$res) throw new \ErrorException(t('message.12002'));
            return $this->response->showResults(Constants::RETURN_SUCCESS, t('message.12001'), []);
        } catch (\Exception $exception) {
            return $this->response->showResults(Constants::SERVER_ERROR, $exception->getMessage(), []);
        }
    }

    /**
     * 删除环境
     */
    public function delete()
    {
        try {
            $rules = ['id' => 'required'];
            $this->validator($rules);
            $id  = $this->request->input('id');
            $res = Environment::query(true)->where('id', $id)->delete();
            if (!$res) throw new \ErrorException(t('message.12002'));
            return $this->response->showResults(Constants::RETURN_SUCCESS, t('message.12001'), []);
        } catch (\Exception $exception) {
            return $this->response->showResults(Constants::SERVER_ERROR, $exception->getMessage(), []);
        }
    }
}
